﻿namespace ApiTemplate.DAL
{
    /// <summary>
    /// 调度任务日志相关数据访问层
    /// </summary>
    public class SchedulerTaskLogDAL : BaseDAL, ISchedulerTaskLogDAL
    {
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="input"></param>
        /// <returns>主键</returns>
        public async Task<string> AddSchedulerTaskLogAsync(SchedulerTaskLog input)
        {
            input.Id = Guid.NewGuid().ToString();
            input.CreatedTime = DateTime.Now;
            await DbContext.Insertable(input).ExecuteCommandAsync();
            return input.Id;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<bool> DeleteSchedulerTaskLogAsync(BaseGuidListInput input)
        {
            await DbContext.Deleteable<SchedulerTaskLog>()
                .Where(x => input.Ids.Contains(x.Id))
                .ExecuteCommandAsync();
            return true;
        }

        /// <summary>
        /// 获取单个
        /// </summary>
        /// <param name="taskId"></param>
        /// <returns></returns>
        public async Task<SchedulerTaskLog> GetSchedulerTaskLogAsync(string taskId)
        {
            return await DbContext.Queryable<SchedulerTaskLog>()
                .Where(x => x.Id == taskId)
                .FirstAsync();
        }

        /// <summary>
        /// 获取指定任务的执行日志
        /// </summary>
        /// <param name="taskId">任务id</param>
        /// <returns></returns>
        public async Task<List<SchedulerTaskLog>> GetTaskLogAsync(string taskId)
        {
            return await DbContext.Queryable<SchedulerTaskLog>()
                .Where(x => x.TaskId == taskId)
                .Skip(0)
                .Take(10)
                .OrderBy(x => x.CreatedTime, SqlSugar.OrderByType.Desc)
                .ToListAsync();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="taskId">老id</param>
        /// <param name="taskId">新id</param>
        /// <returns></returns>
        public async Task<bool> UpdateSchedulerTaskLogByTaskIdAsync(string taskId, string newId)
        {
            SchedulerTaskLog schedulerTaskLog = new SchedulerTaskLog
            {
                TaskId = newId
            };
            await DbContext.Updateable(schedulerTaskLog).UpdateColumns("TaskId").Where(x => x.TaskId == taskId).ExecuteCommandAsync();
            return true;
        }
    }
}
